﻿using StockNet.stocks;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace StockNet.stocks.yahoo
{
    internal class YahooFinanceStockQuery
    {

        // Get stock quote by passing symbol
        public async Task<IEnumerable<StockQuote>> GetStockQuotes(params string[] stockSymbols)
        {
            var stocks = new List<StockQuote>();
            if (stockSymbols == null || stockSymbols.Count() == 0)
            {
                return stocks;
            }

            //s -> symbol, g -> days low, h -> days high
            //c -> change, o -> open, p -> previous close
            //v -> volume, l1 -> last trade (price only) -> close, n -> name
            //Ex: "\"Apple Inc.\",587.44,572.98,36820544"
            string baseURL = "http://finance.yahoo.com/d/quotes.csv?s={0}&f=snpl1v";
            string url = string.Format(baseURL, string.Join("+", stockSymbols));

            //csv content
            string docText = string.Empty;
            try
            {
                var client = new HttpClient();
                var content = await client.GetStringAsync(url);

                var regExString = ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)";

                var regEx = new Regex(regExString, RegexOptions.Singleline);

                using (var stReader = new StringReader(content))
                {
                    var line = stReader.ReadLine();
                    while (line != null)
                    {
                        string[] tokens = line.Split(new char[] { ',' });
                        string[] parts = regEx.Split(line);
                        line = stReader.ReadLine();

                        if (parts.Count() < 5)
                        {
                            continue;
                        }

                        var stock = new StockQuote()
                        {
                            Symbol = parts[0].Trim('"'),
                            Name = parts[1].Trim('"'),
                            PreviousClose = double.Parse(parts[2]),
                            LastTradePrice = double.Parse(parts[3]),
                            Volume = double.Parse(parts[4])
                        };

                        stocks.Add(stock);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }

            return stocks;
        }
    }
}
